package com.object.module.lq.sys.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.object.aop.transaction.LqTransaction;
import com.object.dao.sys.TUserDao;
import com.object.module.lq.sys.service.TOnlineListingService;
import com.object.module.lq.sys.service.TUserService;
import com.object.module.lq.chatroom.entity.TAddRecordEntity;
import com.object.module.lq.chatroom.entity.TGoodFriendEntity;
import com.object.module.lq.sys.entity.TUserEntity;
import com.object.module.lq.sys.ov.TGoodFriendOv;
import com.object.module.lq.sys.ov.TUserAndAddUser;
import com.object.module.lq.sys.service.TRoleService;
import com.object.statuscode.TUserStatusCode;
import com.object.utils.*;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("TUserServiceImpl")
public class TUserServiceImpl extends ServiceImpl<TUserDao, TUserEntity> implements TUserService {

    @Autowired
    private TRoleService roleServicel;


    @Autowired
    private TOnlineListingService onlineListingService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        MyQueryWrapper<TUserEntity> wrapper = new MyQueryWrapper<>(params,TUserEntity.class);
        QueryWrapper<TUserEntity> queryWrapper = wrapper.ConstructQuery();
        Page<TUserEntity> page = wrapper.selectPage(this, queryWrapper);
        for (TUserEntity user : page.getRecords()) {
            user.setRole(roleServicel.getById(user.getUrReId()));
        }

        return new PageUtils(page);
    }


    /**
     * 登录
     *
     * @param user
     * @return
     */
    @Override
    public TUserEntity findLogin(TUserEntity user) {
        QueryWrapper<TUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("ur_username", user.getUrUsername());
        TUserEntity one = getOne(wrapper);
        if (PasswordEncryp.IfPassowrd(user.getUrPassword(), one.getUrPassword())) {
            //密码正确
            return one;
        }
        return null;
    }

    /**
     * 密码修改
     *
     * @param oldpassword
     * @param newpassword
     * @param userId
     * @return
     */
    @Override
    public boolean updatePassword(String oldpassword, String newpassword, Integer userId) {
        TUserEntity userEntity = getById(userId);
        if (PasswordEncryp.IfPassowrd(oldpassword, userEntity.getUrPassword())) {
            //输入的旧密码与数据库的密码一样      把新输入的密码加密并且存储到数据库中去
            userEntity.setUrPassword(PasswordEncryp.getPaawordEncryp(newpassword));
            //修改密码
            boolean b = updateById(userEntity);
            return b;
        }
        return false;
    }

    @Override
    public TUserEntity findById(Integer urId) {
        TUserEntity user = getById(urId);
        user.setRole(roleServicel.getById(user.getUrReId()));
        return user;
    }

    /**
     * 查找用户
     *
     * @param urUsername
     * @return
     */
    @Override
    public TUserEntity infoUrUsername(String urUsername) {
        QueryWrapper<TUserEntity> wrapper = new QueryWrapper<TUserEntity>().eq("ur_username", urUsername);
        TUserEntity userEntity = getOne(wrapper);
        return userEntity;
    }

    /**
     * 查找好友
     *
     * @param userId
     * @param addUserId
     * @return
     */
    @Override
    @Transactional
    public String addUser(Integer userId, Integer addUserId) {
        return "ok";
    }

    /**
     * 获取好友的申请
     * Z
     *
     * @param userId
     * @return
     */
    @Override
    public List<TUserAndAddUser> getAddUsers(Integer userId) {
        return null;
    }

    /**
     * 同意好友
     *
     * @param userId
     * @param agreeUserId
     * @return
     */
    @Override
    @Transactional
    public Q agreeUserId(Integer userId, Integer agreeUserId) {
        return Q.ok();
    }


    /**
     * 获取好友列表
     *
     * @param userId
     * @return
     */
    @Override
    public Q getFriends(Integer userId) {
        return Q.ok();
    }

    /**
     * 登录
     *
     * @param user
     * @param request
     * @return
     */
    @Override
    public Q login(TUserEntity user, HttpServletRequest request) {
        Q q = null;
        //首页判断验证正确
    //    if (PasswordEncryp.IfPassowrd(user.getCaptcha(), user.getCodeEncryption())) {
            TUserEntity user1 = findLogin(user);
            if (user1 != null) {
                //再次判断账号是不是启用
                if (user1.getUrStuats() != TUserStatusCode.enable.stats) {
                    q = Q.error().q("msg", user1.getUrUsername() + "账号被冻结了...");
                } else {
                    //登录成功
                    //保存一下在线用户
                    onlineListingService.saveLogin(user1, request);
                    StpUtil.login(user1.getUrId());
                    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                    q = Q.ok().q("token", tokenInfo).q("user", user1);
                }
            } else {
                q = Q.error().q("msg", "登录失败检查用户名或者密码!");
            }
//        } else {
//            q = QPlus.error().q("msg", "验证码错误!");
//        }
        return q;
    }

    @Override
    public void loginOut() {
        Integer urId = Integer.parseInt(String.valueOf(StpUtil.getLoginId()));
        StpUtil.logoutByTokenValue(StpUtil.getTokenValue());
        onlineListingService.deleteUserId(urId);
    }


    /**
     * 测试事务
     */
    @LqTransaction
    public void testTransaction() {
        TUserEntity tUserEntity = new TUserEntity();
        tUserEntity.setUrName("testYH");
        tUserEntity.setUrPassword("123testYH");
        save(tUserEntity);
        int i = 1 / 0;
    }

    /**
     * 重置密码
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public Q resetYourPassword(Integer userId) {
        TUserEntity userEntity = new TUserEntity();
        userEntity.setUrId(userId);
        userEntity.setUrPassword(PasswordEncryp.getPaawordEncryp("123"));
        boolean updateById = updateById(userEntity);
        return updateById ? Q.ok() : Q.error();
    }

    public Q<List<TUserEntity>> listPage(Map<String, Object> params, Boolean isPage) {
        MyQueryWrapper<TUserEntity> wrapper = new MyQueryWrapper<>(params, TUserEntity.class);
        QueryWrapper<TUserEntity> queryWrapper = wrapper.ConstructQuery();
        if (isPage) {
            return wrapper.pageResponse(this, queryWrapper);
        }
        return new Q<List<TUserEntity>>().ok(list(queryWrapper));
    }


}
